<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Class继承的简介</title>
</head>
<body>
    <h1>Class继承的简介</h1>

    <script>
        // 基本继承
        class Point {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }

            toString() {
                return `(${this.x}, ${this.y})`;
            }
        }

        class ColorPoint extends Point {
            constructor(x, y, color) {
                super(x, y); // 调用父类的constructor(x, y)
                this.color = color;
            }

            toString() {
                return `${super.toString()} in ${this.color}`;
            }
        }

        const cp = new ColorPoint(25, 8, 'green');
        console.log(cp.toString()); // (25, 8) in green

        // 类的继承链
        console.log(Object.getPrototypeOf(ColorPoint) === Point); // true

        // 实际应用：动物类继承
        class Animal {
            constructor(name) {
                this.name = name;
            }

            speak() {
                console.log(`${this.name} makes a sound.`);
            }
        }

        class Dog extends Animal {
            constructor(name, breed) {
                super(name);
                this.breed = breed;
            }

            speak() {
                console.log(`${this.name} barks.`);
            }

            fetch() {
                console.log(`${this.name} fetches the ball.`);
            }
        }

        class Cat extends Animal {
            constructor(name, color) {
                super(name);
                this.color = color;
            }

            speak() {
                console.log(`${this.name} meows.`);
            }

            climb() {
                console.log(`${this.name} climbs the tree.`);
            }
        }

        const dog = new Dog('Max', 'Golden Retriever');
        const cat = new Cat('Luna', 'black');

        dog.speak(); // "Max barks."
        cat.speak(); // "Luna meows."
        dog.fetch(); // "Max fetches the ball."
        cat.climb(); // "Luna climbs the tree."
    </script>
</body>
</html> 